package com.diyunapp.xilinapp.details;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.adapters.RecycleViewSearchListAdapter;
import com.diyunapp.xilinapp.bean.StoreListBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.myapi.OnRecyclerViewItemClickListener;
import com.diyunapp.xilinapp.selfdefine.StatusBarActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/7/28.
 */
public class SearchSetActivity extends StatusBarActivity implements View.OnClickListener {


    @Bind(R.id.searchset_goback_ib)
    ImageButton searchsetGobackIb;
    @Bind(R.id.search_select_tv)
    TextView searchSelectTv;
    @Bind(R.id.search_select_ll)
    LinearLayout searchSelectLl;
    @Bind(R.id.searchset_search_et)
    EditText searchsetSearchEt;
    @Bind(R.id.clear_seachinfo_ib)
    ImageButton clearSeachinfoIb;
    @Bind(R.id.search_do_ll)
    LinearLayout searchDoLl;
    @Bind(R.id.search_history_rv)
    RecyclerView searchHistoryRv;
    @Bind(R.id.search_keylist_rv)
    RecyclerView searchKeylistRv;

    private View head_status_view;
    private View rvHead_view;
    private View rvBottom_view;
    private TextView rvClear_tv;
    private GridLayoutManager rvHisGlMg;
    private RecycleViewSearchListAdapter hisListAdapter;
    private List<String> myHisList;

    private LinearLayoutManager rvKeyLLMg;
    private RecycleViewSearchListAdapter keyListAdapter;
    private List<String> myKeyList;

    private boolean ifGoods = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_set_layout);
        ButterKnife.bind(this);

        initViews();
    }

    private void initViews() {
        head_status_view = findViewById(R.id.searchset_menubar_inc);
        super.MenuWidget(head_status_view);
        searchsetGobackIb.setOnClickListener(this);
        searchSelectLl.setOnClickListener(this);
        searchDoLl.setOnClickListener(this);
        clearSeachinfoIb.setOnClickListener(this);
        searchsetSearchEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.i("zhangxiaoxidebug", "hasFocus = " + hasFocus);
                if (hasFocus) {
                    displayList();
                }
            }
        });
        searchsetSearchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.toString().isEmpty() || MainActivity.isinFreshing) {
                    clearSeachinfoIb.setVisibility(View.GONE);
                    displayList();
                    searchKeylistRv.setVisibility(View.GONE);
                } else {
                    clearSeachinfoIb.setVisibility(View.VISIBLE);
                    searchKeylistRv.setVisibility(View.VISIBLE);
                    searchHistoryRv.setVisibility(View.GONE);
                    displayKeys(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        rvHead_view = LayoutInflater.from(this).inflate(R.layout.searchset_head_layout, null);
        rvBottom_view = LayoutInflater.from(this).inflate(R.layout.searchset_bottom_layout, null);
        rvClear_tv = (TextView) rvBottom_view.findViewById(R.id.clear_seachlist_tv);
        rvClear_tv.setOnClickListener(this);

        //历史搜索记录相关控件初始化
        rvHisGlMg = new GridLayoutManager(this, 1);
        myHisList = new ArrayList<>();
        hisListAdapter = new RecycleViewSearchListAdapter(myHisList);
        hisListAdapter.addHeadView(rvHead_view);
        hisListAdapter.addFootView(rvBottom_view);
        hisListAdapter.setChangeGridLayoutManager(new RecycleViewSearchListAdapter.ChangeGridLayoutManagerSpance() {
            @Override
            public void change(final int size, final boolean isAddHead, final boolean isAddFoot) {
                rvHisGlMg.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        int spanSzie = 1;
                        if (isAddHead) {
                            if (position == 0) {
                                spanSzie = rvHisGlMg.getSpanCount();
                            }
                        }

                        if (isAddFoot) {
                            if (position == size) {
                                spanSzie = rvHisGlMg.getSpanCount();
                            }
                        }
                        return spanSzie;
                    }
                });
            }
        });
        searchHistoryRv.setLayoutManager(rvHisGlMg);
        searchHistoryRv.setAdapter(hisListAdapter);
        hisListAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int data) {
                searchsetSearchEt.setText(myHisList.get(data));
            }
        });

        //搜索关键字模块匹配相关控件初始化
        rvKeyLLMg = new LinearLayoutManager(this);
        myKeyList = new ArrayList<>();
        keyListAdapter = new RecycleViewSearchListAdapter(myKeyList);
        searchKeylistRv.setLayoutManager(rvKeyLLMg);
        searchKeylistRv.setAdapter(keyListAdapter);
        keyListAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int data) {
                searchsetSearchEt.setText(myKeyList.get(data));
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchset_goback_ib:
                finish();
                break;
            case R.id.search_select_ll:
                if (ifGoods) {
                    ifGoods = false;
                    searchSelectTv.setText("店铺");
                } else {
                    ifGoods = true;
                    searchSelectTv.setText("宝贝");
                }
                break;
            case R.id.search_do_ll:
                String searchKeys = searchsetSearchEt.getText().toString();
                if (searchKeys.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "请输入搜索条件", Toast.LENGTH_SHORT).show();
                } else {
                    MainActivity.myDBHelper.insertList(searchKeys);
                    displayList();
                    if (ifGoods) {
                        Intent searchInt = new Intent(this, SearchResultActivity.class);
                        searchInt.putExtra("SearchKeyType", "keyword");
                        searchInt.putExtra("SearchKeyWord", searchKeys);
                        startActivity(searchInt);
                    }
                    else
                    {
                        Intent storeInt = new Intent(this, StoreListActivity.class);
                        storeInt.putExtra("StoreKey", searchKeys);
                        startActivity(storeInt);
                    }
                }
                break;
            case R.id.clear_seachinfo_ib: //执行清空搜素条件操作
                searchsetSearchEt.setText("");
                break;
            case R.id.clear_seachlist_tv: //执行清空历史记录操作后，清空数据库，并隐藏掉历史记录展示控件
                MainActivity.myDBHelper.clearList();
                myHisList.clear();
                searchHistoryRv.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    //显示搜索历史
    private void displayList() {
        myHisList.clear();
        SQLiteDatabase mydatabase = MainActivity.myDBHelper.getReadableDatabase();
        Cursor c = mydatabase.query("search_list_table", null, null, null, null, null, null);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            int index = c.getColumnIndex("search_info");
            Log.i("zhangxiaoxidebug", "search_list = " + c.getString(index));
            myHisList.add(c.getString(index));
            c.moveToNext();
        }
        hisListAdapter.notifyDataSetChanged();
        Log.i("zhangxiaoxidebug", "myHisList size = " + myHisList.size());
        if (myHisList.size() > 0) {
            searchHistoryRv.setVisibility(View.VISIBLE);
        } else {
            searchHistoryRv.setVisibility(View.GONE);
        }
    }

    //显示模糊匹配信息
    public void displayKeys(String keyStr) {
        myKeyList.clear();
        SQLiteDatabase mydatabase = MainActivity.myDBHelper.getReadableDatabase();
        Cursor c = mydatabase.query("search_content_table", null, "content_info like '%" + keyStr + "%'", null, null, null, null);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            int index = c.getColumnIndex("content_info");
            Log.i("zhangxiaoxidebug", "key_list = " + c.getString(index));
            myKeyList.add(c.getString(index));
            c.moveToNext();
        }
        Log.i("zhangxiaoxidebug", "myKeyList size = " + myKeyList.size());
        keyListAdapter.notifyDataSetChanged();
    }
}
